//
//  ComingworkongController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/21.
//  Copyright © 2016年 czd. All rights reserved.
//

#import "ComingworkongController.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OADetailViewController.h"
#import "OADetailDisPatchController.h"
#import "OAUnDoneListCell.h"
#import "PickerChoiceView.h"
#import "TableViewCell.h"


@interface ComingworkongController ()<TFPickerDelegate>
{
    NSInteger selectIndex;
}
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property (nonatomic,strong)NSMutableArray *mutArray;
@end

@implementation ComingworkongController

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    //[self _initview];
        UIImageView *backImageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
       [backImageView setImage:[UIImage imageNamed:@"待办"]];
//self.TableView.backgroundView = backImageView;
    self.TableView.delegate = self;
    self.TableView.dataSource =self;
    self.title = @"待办工作";
    self.name = @"待办工作";
    self.method = @"todoPage";
    self.url = KexchgeneralURL;
   // self.TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshOADetailData" object:nil];
    [self.TableView addHeaderWithCallback:^{
        self.currentPage = 1;

        [self loadData]; //加载网络数据
    }];
    [self.TableView headerBeginRefreshing];
    
    [self.TableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
             [self loadMore];
        }else{
        
            [self.TableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
    
        }
       
    }];
     // 分类搜索
    UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
    [self.TableView registerNib:nib forCellReuseIdentifier:@"TableViewCellID"];
        self.mutArray = [NSMutableArray array];
    
 NSArray *arr = @[@{@"title1":@"请点击此处选择类别",@"title2":@"全部"}];
    for (NSDictionary *dict in arr) {
        
        [self.mutArray addObject:dict];
    }
//


    
}
#pragma mark 刷新数据
-(void)refreshData{
    
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
           [self.dataArray removeAllObjects];
        }
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.TableView reloadData];
        [self.TableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:[NSString stringWithFormat:@"暂时还没有%@哦",self.name]];
        }
    } failure:^(NSError *error) {
     [self.TableView headerEndRefreshing];
        
    }];
 
}
#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
                [self.TableView reloadData];

        [self.TableView footerEndRefreshing];
       
    } failure:^(NSError *error) {
         [self.TableView footerEndRefreshing];
    }];
    
}
//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
    
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * signElement = [[data elementsForName:@"是否编辑"] objectAtIndex:0];
            
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.isSign = [signElement stringValue];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    
     self.title = [NSString stringWithFormat:@"%@(%lu)",self.name,(unsigned long)self.totalCounts];
   
    return array;
}



//- (void)_initview{
//self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, kScreenHeight) style:UITableViewStylePlain];
//self.tableView.delegate = self;
//self.tableView.dataSource = self;
//    [self.view addSubview:self.tableView];
//
//
//
//}
#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row==0) {
    NSDictionary *dict = [self.mutArray objectAtIndex:0];
    
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCellID"];
    cell.backgroundColor = [UIColor clearColor];
    cell.leftLb.text = dict[@"title1"];
    cell.rightLb.text = dict[@"title2"];
   return cell;
}
 else{
    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
    cell.backgroundColor = [UIColor clearColor];
    UnDoneModel * model = self.dataArray[indexPath.row-1];
    cell.model = model;
    return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 0){
PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.view.bounds];
    selectIndex = indexPath.row;
    picker.delegate = self;
    if (indexPath.section == 0) {
        
        picker.selectLb.text = @"部门选择";
        picker.customArr = @[@"全部",@"待办收文",@"待办发文",];
    }

    [self.view addSubview:picker];

}else{


    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UnDoneModel * model = self.dataArray[indexPath.row-1];
     OADetailDisPatchController * detailVC = (OADetailDisPatchController*)[self.storyboard instantiateViewControllerWithIdentifier:@"OADetailDispatchVC"];
        detailVC.fileId = model.fileId;
    
            detailVC.isUnDoWork = YES;
        
        [self.navigationController pushViewController:detailVC animated:YES];
        }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{if(indexPath.row==0)
{
return 40;
}
else{

 UnDoneModel * model = self.dataArray[indexPath.row-1];
    CGFloat  titleFloat  = [OAToolBox sizebyText:model.title font:14 minsWidth:60];
    NSString * desstring = [NSString stringWithFormat:@"%@/%@/%@",model.time,model.state,model.name];
    CGFloat desFloat = [OAToolBox sizebyText:desstring font:14 minsWidth:80];
    return  titleFloat + desFloat + 20;
    }

//return  ( KScreenHeight-64)/10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count+1;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)PickerSelectorIndixString:(NSString *)str{

    NSDictionary *dict = [self.mutArray objectAtIndex:0];
    
    NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    [muDict setObject:str forKey:@"title2"];
    [self.mutArray replaceObjectAtIndex:0 withObject:muDict];
//    [self.mutArray removeObjectAtIndex:selectIndex];
//    [self.mutArray insertObject:muDict atIndex:selectIndex];
    
   if ([str isEqualToString:@"待办收文"]) {
   self.url = Kexchpage;
self.method = @"todoSwPage";
self.name = @"待办收文";
           [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
       
}
if ([str isEqualToString:@"待办发文"]) {
 self.url = Kexchpage;
self.method = @"todoFwPage";
self.name = @"待办发文";
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
}
if ([str isEqualToString:@"全部"]) {
  self.method = @"todoPage";
    self.url = KexchgeneralURL;

self.name = @"待办工作";
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOADetailData" object:nil];
}

  [self.TableView reloadData];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
